import 'dart:async';

import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/pages/mall_app/font_money_sale/font_sale_detail/state.dart';
import 'package:yp/services/api.dart';

import '../../../../helper.dart';
import '../../../../router.dart';

class FontSaleDetailLogic extends GetxController {
  FontSaleDetailState state = FontSaleDetailState();
  Timer surplusTimer;

  String itemNumId;
  String styleNumId;
  String shopId;
  String cat1Id;
  String ecStyleNumId;

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      styleNumId = Get.arguments['styleNumId'];
      shopId = Get.arguments['shopId'];
      cat1Id = Get.arguments['cat1Id'];
    }
    getSurplusMarketDetails();
    keFu();
  }

  void getSurplusMarketDetails() {
    var params = {
      'activity_id': Get.arguments['activity_id'],
      'item_num_id': Get.arguments['item_num_id'],
      'ec_shop_num_id': shopId,
      "channel_num_id": 99,
      "use_platform": 2,
    };
    print(params);
    Api.fontMoneySaleDetail(params).listen((event) {
      print('============================');
      print(event);
      print('============================');

      if (event != null && event['code'] == 0) {
        state.details = event;
        DateTime time = DateTime.now();
        DateTime endTime = DateTime.parse(event['pre_end_time']).toUtc();
        // DateTime dueEndTime =
        //     DateTime.parse(event['due_end_time']).toUtc(); // 付尾款期限
        state.deliveryStartTime = event['delivery_start_time'];
        state.deliveryEndTime = event['delivery_end_time'];
        // DateTime.parse(event['delivery_end_time']).toUtc(); // 发货期限
        // state.deliveryTime = deliveryEndTime.difference(dueEndTime);
        Duration different = endTime.difference(time);
        state.surplusTime = different.inSeconds;
        state.ec_style_num_id = event['ec_style_num_id'];
        startTimer();
        whetherCollection();
        getAndGoThirdShop();
        requestRecommendGoods();
        requestImageAndContent();
      }
      update();
    });
  }

  // 获取是否收藏
  void whetherCollection() {
    var params = {
      "access_token": SpUtil.getString('token'),
      'style_num_id': state.details['style_num_id'],
      'ec_shop_num_id': state.details['shop_num_id']
    };
    Api.whetherCollection(params).listen((event) {
      print('获取是否收藏  =============== event = $event');
      if (event['code'] == 0) {
        state.favorite_sign = event['favorite_sign'];
      }
      update();
    });
  }

  void getAndGoThirdShop() {
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "access_token": SpUtil.getString('token'),
      "ec_shop_num_id": shopId,
    };
    Api.getShopInfo(params).listen((event) {
      if (event != null && event['code'] == 0) {
        if (event['ec_shop_infos'].length > 0) {
          var shoplistes = event['ec_shop_infos'];
          state.shopInfos = {
            'shop_name': shoplistes[0]['ec_shop_name'],
            'shop_id': shoplistes[0]['ec_shop_num_id'],
            'super_ec_shop_num_id': shoplistes[0]['super_ec_shop_num_id'],
            'is_get_home': shoplistes[0]['is_get_home'],
            'is_express': shoplistes[0]['is_express'],
            'service_telphone': shoplistes[0]['service_telphone'],
            'is_pick_up': shoplistes[0]['is_pick_up'],
            'adr': shoplistes[0]['adr'],
            'telphone': shoplistes[0]['telphone'],
            'pickAdrId': shoplistes[0]['sub_unit_num_id'],
            'offShopName': shoplistes[0]['sub_unit_name'],
            'offShopadr': shoplistes[0]['sub_unit_adr'],
            'sub_unit_num_id': shoplistes[0]['sub_unit_num_id'],
            'isSupporySacn': true,
            'free_start_time': '1970-01-01' + shoplistes[0]['free_start_time'],
            'is_express_shops':
                shoplistes[0]['cloud_ec_shop_num_id'] == 1 ? true : false,
            'prv_num_id': shoplistes[0]['prv_num_id'],
            'prv_name': shoplistes[0]['prv_name'],
            'city_num_id': shoplistes[0]['city_num_id'],
            'city_name': shoplistes[0]['city_name'],
            'city_area_num_id': shoplistes[0]['city_area_num_id'],
            'city_area_name': shoplistes[0]['city_area_name'],
            'ec_shop_logo': shoplistes[0]['ec_shop_logo']
          };
          update();
        }
      } else {
        toast(event['massage']);
      }
    });
  }

  // 推荐商品
  void requestRecommendGoods() {
    var token = SpUtil.getString('token');
    if (token == null || token == '') return;
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "cat1_id": cat1Id,
      "is_recommend": 1,
      "shop_id": shopId,
      "shop_num_id": shopId,
      "page_no": 1,
      "page_size": 10,
      "access_token": SpUtil.getString('token')
    };
    Api.recommendGoods(params).listen((event) {
      if (event["code"] == 0) {
        state.recommendGoods = event;
        update();
      }
    });
  }

  void goToThirdShop() {
    SpUtil.remove(Config.GET_SHOP_INFO);
    SpUtil.putObject(Config.GET_SHOP_INFO, state.shopInfos);
    SpUtil.putInt(Config.IS_CHANGE_SHOP,
        SpUtil.getInt('storeShopNum').toString() == shopId ? 0 : 1);
    Get.offAllNamed(RouteConfig.main, arguments: {'isChangeShop': true});
  }

  void requestAddGoods(String ecShopNumId, String itemNumId, String styleNumId,
      String ecStyleNumId,
      {int quantity = 1}) {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": state.nums,
      "ec_shop_num_id": ecShopNumId,
      "item_num_id": itemNumId,
      "style_num_id": styleNumId,
      "ec_style_num_id": state.ec_style_num_id,
      'access_token': SpUtil.getString('token'),
    };
    print(params);
    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        toast('加入购物车成功');
      } else {
        toast(event['message']);
      }
    });
  }

  // 商品规格信息
  void requestImageAndContent() {
    var params = {
      "use_platform": 2,
      "ec_style_num_id": styleNumId,
      "type": "wap"
    };
    Api.goodsDetailImageAndContent(params).listen((event) {
      if (event['code'] == 0) {
        state.richText = event;
        update();
      }
    });
  }

  // void requestAddToFavorite() {
  //   if (state.favorite_sign == false) {
  //     var params = {
  //       "use_platform": 2,
  //       'style_num_id': state.details['style_num_id'],
  //       'ec_shop_num_id': state.details['shop_num_id'],
  //       "access_token": SpUtil.getString("token")
  //     };
  //     Api.addGoodsToFavorite(params).listen((event) {
  //       if (event['code'] == 0) {
  //         toast('加入收藏成功');
  //         state.favorite_sign = true;
  //       }
  //       update();
  //     });
  //   } else {
  //     var params = {
  //       'style_num_id': state.details['style_num_id'],
  //       'ec_shop_num_id': state.details['shop_num_id'],
  //       'access_token': SpUtil.getString('token'),
  //     };
  //     Api.collectListsDelete(params).listen((event) {
  //       if (event['code'] == 0) {
  //         toast('取消收藏成功');
  //         state.favorite_sign = false;
  //       }
  //       update();
  //     });
  //   }
  // }

  // void requestDetail() async {
  //   keFu();
  //   var params = {
  //     "channel_num_id": 99,
  //     "use_platform": 2,
  //     "style_num_id": styleNumId,
  //     "shop_id": shopId,
  //     "item_num_id": itemNumId,
  //     "access_token": SpUtil.getString('token'),
  //     "prv_num_id": "320000",
  //     "city_num_id": "320500",
  //     "city_area_num_id": "320583",
  //     "user_num_id": SpUtil.getInt('empeNumId'),
  //     'customer_type': 3,
  //   };

  //   Api.goodsDetail(params).listen((event) {
  //     if (event["code"] == 0) {
  //       state.goodsDetail = event;
  //       cat1Id = event['cat1_id']?.toString() ?? '';
  //       ecStyleNumId = event['spec_item_detail'] != null
  //           ? '${event['spec_item_detail']['ec_style_num_id']}'
  //           : '';
  //       requestRecommendGoods();
  //       requestComment();
  //       requestImageAndContent();
  //       promotionalInformation();
  //       specificationParameters();
  //       if (SpUtil.getString('token') != null &&
  //           SpUtil.getString('token').isNotEmpty) {
  //         requestAvailableCoupons();
  //         whetherCollection();
  //       }
  //     }
  //     update();
  //   });
  // }

  void goShop() {
    if (SpUtil.getString('token') == null ||
        SpUtil.getString('token').isEmpty) {
      Get.toNamed(RouteConfig.mallLogin).then((value) {
        // if (SpUtil.getString('token') != null &&
        //     SpUtil.getString('token').isNotEmpty) {
        //   logic.requestDetail();
        // }
      });
    } else {
      Get.toNamed(RouteConfig.orderSettlements, arguments: {
        'shop_id': state.details['shop_num_id'],
        "item_num_id": state.details['item_num_id'],
        "style_num_id": state.details['style_num_id'],
        "ec_style_num_id": state.details['ec_style_num_id'],
        'shopnum': 1,
      });
    }
  }

  void goSurplusShop() {
    if (SpUtil.getString('token') == null ||
        SpUtil.getString('token').isEmpty) {
      Get.toNamed(RouteConfig.mallLogin).then((value) {
        // if (SpUtil.getString('token') != null &&
        //     SpUtil.getString('token').isNotEmpty) {
        //   logic.requestDetail();
        // }
      });
    } else {
      Get.toNamed(RouteConfig.frontSaleOrder, arguments: {
        "ecactivity_id": Get.arguments['activity_id'],
        'shop_id': state.details['shop_num_id'],
        "item_num_id": state.details['item_num_id'],
        "style_num_id": state.details['style_num_id'],
        "ec_style_num_id": state.details['ec_style_num_id'],
        'shopnum': 1
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
  }

  void startTimer() {
    // 设置 1 秒回调一次
    const period = const Duration(seconds: 1);
    surplusTimer = Timer.periodic(period, (timer) {
      if (state.surplusTime <= 0) {
        // 倒计时秒数为0，取消定时器
        print('我被取消了  ');
        cancelTimer();
        // getData();
      }
      //更新界面
      //秒数减一，因为一秒回调一次
      state.surplusTime--;
      state.countContent = constructTime(state.surplusTime);
      update();
    });
  }

  void cancelTimer() {
    if (surplusTimer != null) {
      surplusTimer.cancel();
      surplusTimer = null;
    }
  }

  String constructTime(num mss) {
    int days = (mss / (60 * 60 * 24)).floor();
    int hours = ((mss % (60 * 60 * 24)) / (60 * 60)).floor();
    int minutes = ((mss % (60 * 60)) / 60).floor();
    int seconds = (mss % 60).floor();
    return formatTime(days) +
        "天" +
        formatTime(hours) +
        "时" +
        formatTime(minutes) +
        "分" +
        formatTime(seconds) +
        "秒";
  }

  // 数字格式化，将 0~9 的时间转换为 00~09
  String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  // 获取客服信息
  void keFu() {
    print('获取客服信息 ======== 获取客服信息11111111');
    Api.MaterialGoodsSelect1({"config_name": "platform_ec_shop_num_id"})
        .listen((event) {
      print('获取客服信息 ======== 获取客服信息 ********  event = $event');
      var configValue = event["config_value"];
      Api.getAccessID(configValue.toString()).listen((event) {
        print('获取客服信息 ======== 获取客服信息  event = $event');
        // state.accessID = event["access_id"];
        state.keFuString = event['access_id'];
        update();
      });
    });
  }
}
